import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Input } from 'antd';
import { SizeType } from 'antd/lib/config-provider/SizeContext';
import { generateValidateCode } from '@/apis/user/index';
//验证码
interface VerificationCodeInputProps {
    onChange?: (value: string | undefined) => void
    value?: string
    size: SizeType
    disabled?: boolean
    placeholder?: string
    Icon?: React.ReactNode
}
const VerificationCodeInput = forwardRef((props: VerificationCodeInputProps, ref: React.Ref<any>) => {
    const { onChange, value, Icon, size, disabled, placeholder } = props
    const [codeUrl, setCodeUrl] = useState('');
    const [codeVal, setCodeVal] = useState(value);
    const [imgKey, setimgKey] = useState('')
    //ref分发给组件内的方法以及自定义属性
    useImperativeHandle(ref, () => {
        return {
            getCodeUrl: getCodeUrlApi,
            imgKey: imgKey
        }
    })

    function changeHandle(e: React.ChangeEvent<HTMLInputElement>) {
        let val = e.target.value || "";
        val = val.trim();
        setCodeVal(val);
        onChange && onChange(val);
    }
    //获取验证码
    async function getCodeUrlApi() {
        let res = await generateValidateCode({})
        setCodeUrl(res.data.img || '')
        setimgKey(res.data.imgKey || '')
    }
    function refreshCodeHandle() {
        getCodeUrlApi()
        setCodeVal(undefined);
        onChange && onChange(undefined);
    }

    useEffect(() => {
        setCodeVal(value);
    }, [value]);

    useEffect(() => {
        getCodeUrlApi()
        return
    }, []);

    return (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Input
                value={codeVal}
                size={size}
                disabled={disabled}
                placeholder={placeholder}
                onChange={changeHandle}
                style={{ width: '60%' }}
                maxLength={4}
                prefix={Icon}
            />
            <img alt='' src={`data:image/png;base64,${codeUrl}`} onClick={refreshCodeHandle} style={{ width: '35%', height: '100%', objectFit: 'cover', cursor: 'pointer' }} />
        </div>
    )
})

export default VerificationCodeInput